//
//  AppDelegate.m
//  ZhuoxinAgriculture
//
//  Created by KKING on 2016/11/8.
//  Copyright © 2016年 KKING. All rights reserved.
//

#import "AppDelegate.h"
#import "HMTabBarController.h"
#import "HMGuideController.h"
#import "ZXLoginViewController.h"
#import "IQKeyboardManager.h"
#import "HMNavigationController.h"
#import "UMessage.h"
#import "SNMYNavigationController.h"

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate

- (void)privateMethod:(NSString *)viewControllerString
{
    /** 创建 Window */
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    /** 创建 ViewController*/
    UIViewController * viewController = [[NSClassFromString(viewControllerString) alloc] init];
    
    /** 创建 NavigationController */
    SNMYNavigationController * navigationController = [[SNMYNavigationController alloc] initWithRootViewController:viewController];
    /** 设置根控制器 */
    [self.window setRootViewController:navigationController];

    /** 显示window */
    [self.window makeKeyAndVisible];
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    /** 跳转自定义控制器 */
    {
        NSString * filePath = [[NSBundle mainBundle] pathForResource:@"policyfile.plist" ofType:nil];
        NSDictionary * dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
        
        BOOL USECustomViewController =  [dict[@"USECustomViewController"] boolValue];
        if (USECustomViewController == YES) {
            
            NSLog(@"NSHomeDirectory() = %@",NSHomeDirectory());
            
            if ([NSHomeDirectory() containsString:@"/Users/stone"]) {
                // my mac
                [self privateMethod:@"SNPlanListViewController"];
//                [self privateMethod:@"DecisionMakerListViewController"];
                return YES;
            }
        }
    }
    
    //判断是否登录
    // [self checkLogin];
    
    //设置IQKeyboard
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    
    //设置友盟推送
    [self setupUMessageWithOptions:launchOptions];
    
    //创建窗口
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor lightGrayColor];
    ZXLoginViewController *loginView = [[ZXLoginViewController alloc]init];
    
    
    HMGuideController *guideVc = [[HMGuideController alloc]init];
//    HMTabBarController *tabBarVc = [[HMTabBarController alloc]init];
    //判断是否是新版本
    if ([self isNew]) {
        self.window.rootViewController = guideVc;///guideVc
    }else{
        self.window.rootViewController = [[HMNavigationController alloc]initWithRootViewController:loginView];///tabbarVc
    }
    
    //显示
    [self.window makeKeyAndVisible];
    
    //MARK: - 状态栏设置为白色
    application.statusBarHidden = NO;
    application.statusBarStyle = UIStatusBarStyleLightContent;

    dispatch_async(dispatch_get_main_queue(), ^{
        
        [ZXHTTPManager startMonitoring];
    });
    
    return YES;
}

-(void)checkLogin{
    NSString *username = [[NSUserDefaults standardUserDefaults]objectForKey:@"username_key"];
    NSString *password = [[NSUserDefaults standardUserDefaults]objectForKey:@"password_key"];
    
    if (username && password) {
        [self loginSuccess];
    }
    else
    {
        [self loginOut];
    }
    
    //MARK: 登录成功的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"LoginSuccess" object:nil];
    //MARK: 注销之后的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginOut) name:@"LoginOut" object:nil];

}


-(void)loginSuccess{
    
    self.window.rootViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateInitialViewController];
}

-(void)loginOut{
    
    self.window.rootViewController = [[UIStoryboard storyboardWithName:@"Login" bundle:nil] instantiateInitialViewController];
    
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}




//逻辑优化

-(BOOL)isNew{
    
    //获取info.plist文件
    NSDictionary *dict = [NSBundle mainBundle].infoDictionary;
    //获取当前版本号:
    NSString *str = dict[@"CFBundleShortVersionString"];
    
    //MARK: - 取出应用当前版本号,和读取之前版本号进行判断
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //取值
    NSString *oldStr = [defaults objectForKey:@"app_version"];
    //创建根视图之前 增加判断
    if ( [str isEqualToString:oldStr] ) {
        
        return NO;
    }else{
        [defaults setObject:str forKey:@"app_version"];
        [defaults synchronize];
        
        return YES;
    }
}


- (void)setupUMessageWithOptions:(NSDictionary *)launchOptions{
    
    //友盟推送
    [UMessage startWithAppkey:@"583da0f4677baa2b0f001430" launchOptions:launchOptions];
    
    //iOS10必须加下面这段代码。
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate=self;
    UNAuthorizationOptions types10=UNAuthorizationOptionBadge|  UNAuthorizationOptionAlert|UNAuthorizationOptionSound;
    [center requestAuthorizationWithOptions:types10   completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            //点击允许
            //这里可以添加一些自己的逻辑
        } else {
            //点击不允许
            //这里可以添加一些自己的逻辑
        }
    }];
    
    //打开日志，方便调试
//    [UMessage setLogEnabled:YES];
    //高级功能加入
    
    
    if ( [[[UIDevice currentDevice] systemVersion] floatValue] >= 10) {
        /*ios10以上*/
        UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:@"action1" title:@"打开" options:UNNotificationActionOptionForeground];
        
        UNTextInputNotificationAction *action2 = [UNTextInputNotificationAction actionWithIdentifier:@"action2" title:@"清除" options:UNNotificationActionOptionDestructive textInputButtonTitle:@"textInputButtonTitle" textInputPlaceholder:@"textInputPlaceholder"];
        
        UNNotificationCategory *category1 = [UNNotificationCategory categoryWithIdentifier:@"Category1" actions:@[action2,action1]  intentIdentifiers:@[@"action1",@"action2"] options:UNNotificationCategoryOptionCustomDismissAction];
        
        UNNotificationAction *action3 = [UNNotificationAction actionWithIdentifier:@"action3" title:@"查看" options:UNNotificationActionOptionForeground];
        
        
        UNNotificationAction *action4 = [UNNotificationAction actionWithIdentifier:@"action4" title:@"关闭" options:UNNotificationActionOptionAuthenticationRequired];
        
        UNNotificationCategory *category2 = [UNNotificationCategory categoryWithIdentifier:@"Category2" actions:@[action3,action4]  intentIdentifiers:@[@"action3",@"action4"] options:UNNotificationCategoryOptionCustomDismissAction];
        //注册
        [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category1,category2, nil]];
        
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) {
            NSLog(@"completionHandler");
        }];
        
    }else{
        /*ios10以下*/
        
        UIMutableUserNotificationAction * action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1";
        action1.title=@"策略1行为1";
        action1.activationMode = UIUserNotificationActivationModeForeground;
        action1.destructive = YES;
        
        UIMutableUserNotificationAction * action2 = [[UIMutableUserNotificationAction alloc] init];
        action2.identifier = @"action2";
        action2.title=@"策略1行为2";
        action2.activationMode = UIUserNotificationActivationModeBackground;
        action1.activationMode = UIUserNotificationActivationModeForeground;
        action1.destructive = YES;
        
        UIMutableUserNotificationCategory * category1 = [[UIMutableUserNotificationCategory alloc] init];
        category1.identifier = @"Category1";
        [category1 setActions:@[action2,action1] forContext:(UIUserNotificationActionContextDefault)];
        
        //注册
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:[NSSet setWithObjects: category1, nil]];
        
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
    }
    
    //推送注册
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
    [UNUserNotificationCenter currentNotificationCenter].delegate = self;
    
}

//iOS10以下使用这个方法接收通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
    // 当应用在前台时，不推送
    if([UIApplication sharedApplication].applicationState == UIApplicationStateActive){
        //关闭对话框
        [UMessage setAutoAlert:NO];
    }
    //
    [[NSNotificationCenter defaultCenter] postNotificationName:@"userInfoNotification" object:self userInfo:userInfo];
    [UMessage didReceiveRemoteNotification:userInfo];
    
}


//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    NSLog(@"前台括号外：userNotificationCenter:willPresentNotification");
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        
        NSLog(@"前台括号内：userNotificationCenter:willPresentNotification");
        
        //可以自定义前台弹出框
        
        //        [[NSNotificationCenter defaultCenter] postNotificationName:@"userInfoNotification" object:self userInfo:userInfo];
        
        //应用处于前台时的远程推送接受
        //关闭友盟自带的弹出框
        [UMessage setAutoAlert:NO];
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    //当应用处于前台时提示设置，需要哪个可以设置哪一个
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}


//iOS10新增：处理后台点击通知的代理方法
//iOS10以后接收的方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
 
    NSLog(@"后台括号外：userNotificationCenter:didReceiveNotificationResponse");
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        NSLog(@"后台括号内：userNotificationCenter:didReceiveNotificationResponse");
        
        //        代理方法
        [[NSNotificationCenter defaultCenter] postNotificationName:@"userInfoNotification" object:self userInfo:userInfo];
        
        [UMessage didReceiveRemoteNotification:userInfo];
        if([response.actionIdentifier isEqualToString:@"*****你定义的action id****"])
        {
            
            
        }else
        {
            
        }
        //这个方法用来做action点击的统计
        [UMessage sendClickReportForRemoteNotification:userInfo];
        
    }else{
        //应用处于后台时的本地推送接受
        
    }
    
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    
    NSString *error_str = [NSString stringWithFormat: @"%@", error];
    NSLog(@"Failed to get token, error:%@", error_str);
    
}
//获取device_Token
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [UMessage registerDeviceToken:deviceToken];
    NSString *dt = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                     stringByReplacingOccurrencesOfString: @">" withString: @""]
                    stringByReplacingOccurrencesOfString: @" " withString: @""];
    
    //调起本地存储
    //    NSDictionary *dict = @{@"123":@"234",@"567":@"890"};
    
    //偏好设置
    // 获取用户偏好设置对象
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    // 保存用户偏好设置
    [defaults setObject:dt forKey:@"deviceToken"];
    [defaults synchronize];
    //    // 读取用户偏好设置
    
    NSString *det = [defaults stringForKey:@"deviceToken"];
    
    NSLog(@"det:%@",det);
    
    
    //    //获取路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"path:%@",path);
    


        UIAlertController *avc = [UIAlertController alertControllerWithTitle:@"测试推送,请复制下面token" message:dt preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *done = [UIAlertAction actionWithTitle:@"复制" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = dt;
        }];
        [avc addAction:done];
    
//    [self.window.rootViewController presentViewController:avc animated:YES completion:nil];
}


@end
